import JSZip from 'jszip';
import { BOX_TYPE_ENUM, COLUMN_TYPE_MAP, JAVA_TYPE_ENUM } from '@/views/tool/generate/const';
import { saveAs } from 'file-saver'

export function build(data: GenerateRecord) {
  const caseTableName = titleCase(data.tableName);

  const viewData = createView(data)

  const indexVue = viewData.index;

  const editVue = viewData.edit;

  const detailVue = viewData.detail;

  const apiTs = viewData.api;

  const recordTs = viewData.record;

  const mockTs = viewData.mock;

  const zip = new JSZip()

  const indexBlob = new Blob([indexVue]);

  const editBlob = new Blob([editVue]);

  const detailBlob = new Blob([detailVue]);

  const apiBlob = new Blob([apiTs]);

  const recordBlob = new Blob([recordTs]);

  const mockBlob = new Blob([mockTs]);

  // @ts-ignore
  zip.file(`src/views/${data.folder}/${data.tableName}/index.vue`, indexBlob, { blob: true });
  // @ts-ignore
  zip.file(`src/views/${data.folder}/${data.tableName}/edit.vue`, editBlob, { blob: true });
  // @ts-ignore
  zip.file(`src/views/${data.folder}/${data.tableName}/detail.vue`, detailBlob, { blob: true });
  // @ts-ignore
  zip.file(`src/api/${data.folder}/${data.tableName}.ts`, apiBlob, { blob: true });
  // @ts-ignore
  zip.file(`src/global/record/${data.folder}/${caseTableName}Record.ts`, recordBlob, { blob: true });
  // @ts-ignore
  zip.file(`mock/${data.folder}/${data.tableName}.ts`, mockBlob, { blob: true });
  zip.generateAsync({
    type: 'blob'
  }).then((bigeBlob) => {
    saveAs(bigeBlob, 'bige')
  })
}

export function preview(data: GenerateRecord): ViewPageRecord {
  return createView(data)
}

function createView(data: GenerateRecord): ViewPageRecord {
  const caseTableName = titleCase(data.tableName);

  const tableKey = data.tableList.find(item => item.isKey)?.columnName || `${data.tableName}Id`;

  if (data.folder.indexOf('/') === 0) {
    data.folder = data.folder.replace('/', '');
  }
  if (data.apiUrl.indexOf('/') === 0) {
    data.apiUrl = data.apiUrl.replace('/', '');
  }

  let queryFormItems = ``;

  let tableColumns = '';

  let columns = '';

  let queryParams = '';

  let editFormItems = '';

  let rules = '';

  let editParams = '';

  let detailFormItems = '';

  let records = '';

  let dictTypeKeyList: string[] = [];

  let dictTypeStrList: string[] = [];


  for (let item of data.tableList) {
    let queryFormItem = "";
    if (item.boxType == BOX_TYPE_ENUM.select || item.boxType == BOX_TYPE_ENUM.radio) {
      if (item.dictType) {
        queryFormItem = `
        <el-form-item label="${item.columnNotes}" prop="${item.columnName}" v-if="showSearch">
          <el-select
              v-model="queryParams.${item.columnName}"
              placeholder="请选择${item.columnNotes}"
              clearable
              @keyup.enter.native="handleQuery"
          >
            <el-option
                v-for="item in ${item.dictType}"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>`
      } else {
        queryFormItem = `
        <el-form-item label="${item.columnNotes}" prop="${item.columnName}" v-if="showSearch">
          <el-select
              v-model="queryParams.${item.columnName}"
              placeholder="请选择${item.columnNotes}"
              clearable
              @keyup.enter.native="handleQuery"
          >
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>`
      }

    } else if (item.boxType == BOX_TYPE_ENUM.checkbox) {
      if (item.dictType) {
        queryFormItem = `
        <el-form-item label="${item.columnNotes}" prop="${item.columnName}" v-if="showSearch">
          <el-select
              v-model="queryParams.${item.columnName}"
              multiple
              collapse-tags
              placeholder="请选择${item.columnNotes}"
              clearable
              @keyup.enter.native="handleQuery"
          >
            <el-option
                v-for="item in ${item.dictType}"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>`
      } else {
        queryFormItem = `
        <el-form-item label="${item.columnNotes}" prop="${item.columnName}" v-if="showSearch">
          <el-select
              v-model="queryParams.${item.columnName}"
              multiple
              collapse-tags
              placeholder="请选择${item.columnNotes}"
              clearable
              @keyup.enter.native="handleQuery"
          >
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>`
      }
    } else if (item.boxType == BOX_TYPE_ENUM.datePicker) {
      queryFormItem = `
        <el-form-item label="${item.columnNotes}" prop="${item.columnName}" v-if="showSearch">
          <el-date-picker
              v-model="queryParams.${item.columnName}"
              type="datetime"
              placeholder="请选择${item.columnNotes}"
              value-format="YYYY-MM-DD HH:mm:ss"
              clearable
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>`
    } else {
      queryFormItem = `
        <el-form-item label="${item.columnNotes}" prop="${item.columnName}" v-if="showSearch">
          <el-input
              v-model="queryParams.${item.columnName}"
              placeholder="请输入${item.columnNotes}"
              clearable
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>`
    }

    let tableColumn = `
        <el-table-column label="${item.columnNotes}" prop="${item.columnName}" align="center" v-if="columns.${item.columnName}.visible" />`
    if (item.dictType) {
      tableColumn = `
        <el-table-column label="${item.columnNotes}" prop="${item.columnName}" align="center" v-if="columns.${item.columnName}.visible">
          <template #default="scope">
            <dict-tag :options="${item.dictType}" :value="scope.row.${item.columnName}" />
          </template>
        </el-table-column>`
    }

    const column = `
  ${item.columnName}: { label: '${item.columnNotes}', visible: true },`

    const queryParam = `
  ${item.columnName}: null,`

    let editFormItem = '';
    if (item.boxType == 'select') {
      if (item.dictType) {
        editFormItem = `
      <el-form-item label="${item.columnNotes}" prop="${item.columnName}">
        <el-select v-model="form.${item.columnName}" placeholder="请选择${item.columnNotes}">
          <el-option
              v-for="item in ${item.dictType}"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>`
      } else {
        editFormItem = `
      <el-form-item label="${item.columnNotes}" prop="${item.columnName}">
        <el-select v-model="form.${item.columnName}" placeholder="请选择${item.columnNotes}">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>`
      }
    } else if (item.boxType == BOX_TYPE_ENUM.radio) {
      if (item.dictType) {
        editFormItem = `
      <el-form-item label="${item.columnNotes}" prop="${item.columnName}" class="item-describe">
        <el-radio-group v-model="form.${item.columnName}">
          <el-radio
              v-for="item in ${item.dictType}"
              :key="item.value"
              :value="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>`
      } else {
        editFormItem = `
      <el-form-item label="${item.columnNotes}" prop="${item.columnName}" class="item-describe">
        <el-radio-group v-model="form.${item.columnName}">
          <el-radio value="" >请选择字典生成</el-radio>
        </el-radio-group>
      </el-form-item>`
      }
    } else if (item.boxType == BOX_TYPE_ENUM.checkbox) {
      if (item.dictType) {
        editFormItem = `
      <el-form-item label="${item.columnNotes}" prop="${item.columnName}" class="item-describe">
        <el-checkbox-group v-model="form.${item.columnName}">
          <el-checkbox
              v-for="item in ${item.dictType}"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-checkbox-group>
      </el-form-item>`
      } else {
        editFormItem = `
      <el-form-item label="${item.columnNotes}" prop="${item.columnName}" class="item-describe">
        <el-checkbox-group v-model="form.${item.columnName}">
          <el-checkbox label="请选择字典生成" value="" />
        </el-checkbox-group>
      </el-form-item>`
      }
    } else if (item.boxType == BOX_TYPE_ENUM.inputNumber) {
      editFormItem = `
      <el-form-item label="${item.columnNotes}" prop="${item.columnName}">
        <el-input-number v-model="form.${item.columnName}" :min="1" placeholder="请输入${item.columnNotes}" />
      </el-form-item>`
    } else if (item.boxType == BOX_TYPE_ENUM.datePicker) {
      editFormItem = `
      <el-form-item label="${item.columnNotes}" prop="${item.columnName}">
        <el-date-picker
            v-model="form.${item.columnName}"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择${item.columnNotes}"
        />
      </el-form-item>`
    } else if (item.boxType == BOX_TYPE_ENUM.textarea) {
      editFormItem = `
      <el-form-item label="${item.columnNotes}" prop="${item.columnName}" class="item-describe">
        <el-input v-model="form.${item.columnName}" type="textarea" placeholder="请输入${item.columnNotes}" />
      </el-form-item>`
    } else {
      editFormItem = `
      <el-form-item label="${item.columnNotes}" prop="${item.columnName}">
        <el-input v-model="form.${item.columnName}" placeholder="请输入${item.columnNotes}" />
      </el-form-item>`
    }

    let rule = '';
    if (item.required) {
      let changeList = [
        BOX_TYPE_ENUM.checkbox,
        BOX_TYPE_ENUM.select,
        BOX_TYPE_ENUM.radio,
        BOX_TYPE_ENUM.datePicker
      ]
      if (changeList.includes(item.boxType)) {
        rule = `
  ${item.columnName}: [
    { required: true, message: '${item.columnNotes}不能为空', trigger: 'change' }
  ],`
      } else {
        rule = `
  ${item.columnName}: [
    { required: true, message: '${item.columnNotes}不能为空', trigger: 'blur' }
  ],`
      }
    }

    let editParam = ``
    if (item.boxType == BOX_TYPE_ENUM.checkbox) {
      editParam = `
    ${item.columnName}: [],`
    } else {
      editParam = `
    ${item.columnName}: null,`
    }

    let detailFormItem = ``
    if (item.dictType) {
      detailFormItem = `
        <el-form-item label="${item.columnNotes}" prop="${item.columnName}"${item.boxType == BOX_TYPE_ENUM.textarea ? ' class="item-describe"' : ''}>
          <dict-tag :options="${item.dictType}" :value="form.${item.columnName}" />
        </el-form-item>`
    } else {
      detailFormItem = `
        <el-form-item label="${item.columnNotes}" prop="${item.columnName}"${item.boxType == BOX_TYPE_ENUM.textarea ? ' class="item-describe"' : ''}>
          {{ form.${item.columnName} }}
        </el-form-item>`
    }

    const record = `
  /** ${item.columnNotes} */
  ${item.columnName}?: ${(item.columnType || COLUMN_TYPE_MAP[JAVA_TYPE_ENUM.string]) + (item.boxType == BOX_TYPE_ENUM.checkbox ? '[]' : '')};`

    if (item.dictType) {
      dictTypeKeyList.push(item.dictType)
      dictTypeStrList.push(`"${item.dictType}"`)
    }

    queryFormItems += queryFormItem;
    tableColumns += tableColumn;
    columns += column;
    queryParams += queryParam;
    editFormItems += editFormItem;
    rules += rule;
    editParams += editParam;
    detailFormItems += detailFormItem;
    records += record;
  }

  const indexVue = `<script setup lang="ts" name="${caseTableName}">
import editPage from './edit.vue';
import detailPage from './detail.vue';
import { list${caseTableName}Api, del${caseTableName}Api } from '@/api/system/${data.tableName}';

const { proxy } = getCurrentInstance();
${dictTypeKeyList.length ? `\nconst { ${dictTypeKeyList.join(', ')} } = useDict(${dictTypeStrList.join(', ')});\n` : ''}
// 加载
const loading = ref(false);

// 导出遮罩层
const exportLoading = ref(false);

// 搜索栏元素
const query${caseTableName}Ref = ref(null);

// 表单Id
const id = ref(null);

// 选中数组
const selection = ref<${caseTableName}Record[]>([]);

// 非单个禁用
const single = ref(true);

// 非多个禁用
const multiple = ref(true);

// 切换搜索条件
const showSearch = ref(false);

// ${data.tableNotes}列表
const ${data.tableName}List = ref<${caseTableName}Record[]>([]);

// 弹出层标题
const title = ref('');

// 编辑弹出层
const openEdit = ref(false);

// 详情弹出层
const openDetail = ref(false);

//总条数
const total = ref(0);

// 列信息
const columns = ref<TableColumnsRecord>({
  colNo: { label: '序号', visible: true },${columns}
  operate: { label: '操作', visible: true }
});

// 查询参数
const queryParams = ref<${caseTableName}Record>({
  pageNum: 1,
  pageSize: 10,${queryParams}
});

/** 查询${data.tableNotes}列表 */
function getList() {
  loading.value = true;
  list${caseTableName}Api(queryParams.value).then(response => {
    ${data.tableName}List.value = response.rows;
    total.value = response.total;
    loading.value = false;
    ${data.tableName}List.value.forEach((item, index) => {
      item['colNo'] = sequenceNo(index, queryParams.value);
    });
  });
}

/** 关闭弹窗 */
function closeDialog(refresh: boolean) {
  if (refresh) {
    getList();
  }
  openEdit.value = false;
  openDetail.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  query${caseTableName}Ref.value.resetFields();
  handleQuery();
}

/** 切换按钮操作 */
function changSearch() {
  showSearch.value = !showSearch.value;
}

/** 多选框选中数据 */
function handleSelectionChange(selectionList: ${caseTableName}Record[]) {
  selection.value = selectionList;
  single.value = selectionList.length !== 1;
  multiple.value = !selectionList.length;
}

/** 新增按钮操作 */
function handleAdd() {
  id.value = null;
  openEdit.value = true;
  title.value = '新增${data.tableNotes}';
}

/** 修改按钮操作 */
function handleUpdate(row: ${caseTableName}Record) {
  id.value = row.${tableKey};
  openEdit.value = true;
  title.value = '修改${data.tableNotes}';
}

/** 详情按钮操作 */
function handleDetails(row: ${caseTableName}Record) {
  id.value = row.${tableKey};
  openDetail.value = true;
  title.value = '${data.tableNotes}详情';
}

/** 删除按钮操作 */
function handleDelete(row: ${caseTableName}Record | any) {
  let ids = [];
  let colNos = [];
  if (row.${tableKey}) {
    ids = [row.${tableKey}];
    colNos = [row.colNo];
  } else {
    selection.value.forEach(item => {
      ids.push(item.${tableKey});
      colNos.push(item.colNo);
    });
  }

  // @ts-ignore
  proxy.$modal.confirm('是否确认删除序号为"' + colNos + '"的数据项?').then(() => {
    return del${caseTableName}Api(ids);
  }).then(() => {
    getList();
    // @ts-ignore
    proxy.$modal.msgSuccess('删除成功');
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  download('${data.apiUrl}/export', {
    ...queryParams.value
  }, \`${data.tableNotes}_\${new Date().getTime()}.xlsx\`);
}

getList();
</script>

<template>
  <div class="app-container">
    <div class="back-item">
      <el-form :model="queryParams" ref="query${caseTableName}Ref" :inline="true" label-width="68px">${queryFormItems}
        <el-form-item class="item-search">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button type="warning" icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button
              :icon="showSearch ? 'CaretTop' : 'CaretBottom'"
              @click="changSearch"
          >
            {{ showSearch ? '折叠' : '更多' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="back-item">
      <div class="table-top mb8">
        <div class="title title-left">
          ${data.tableNotes}列表
        </div>
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-has-permi="['${data.modular}:add']"
        >新增
        </el-button>
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-has-permi="['${data.modular}:remove']"
        >删除
        </el-button>
        <el-button
            type="warning"
            plain
            icon="Download"
            :loading="exportLoading"
            @click="handleExport"
            v-has-permi="['${data.modular}:export']"
        >导出
        </el-button>
        <span class="table-top-line" />
        <right-toolbar @queryTable="getList" :columns="columns" />
      </div>
      <el-table
          v-loading="loading"
          :data="${data.tableName}List"
          stripe
          v-tablesticky
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" prop="colNo" align="center" width="55" v-if="columns.colNo.visible" />${tableColumns}
        <el-table-column label="操作" prop="operate" align="center" fixed="right" width="120" v-if="columns.operate.visible">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                  v-has-permi="['${data.modular}:edit']"
              />
            </el-tooltip>
            <el-tooltip content="详情" placement="top">
              <el-button
                  link
                  type="primary"
                  icon="Document"
                  @click="handleDetails(scope.row)"
                  v-has-permi="['${data.modular}:query']"
              />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  class="text-danger"
                  v-has-permi="['${data.modular}:remove']"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
          :total="total"
          open-fixed
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
      <div class="line-magin" />
    </div>

    <!-- 添加或修改${data.tableNotes}对话框 -->
    <edit-page v-if="openEdit" :id="id" :title="title" @closeDialog="closeDialog" />
    <detail-page v-if="openDetail" :id="id" :title="title" @closeDialog="closeDialog" />
  </div>
</template>

<style lang="scss" scoped>

</style>`

  const editVue = `<script setup lang="ts" name="${caseTableName}Edit">
import { get${caseTableName}Api, update${caseTableName}Api, add${caseTableName}Api } from '@/api/system/${data.tableName}';

const { proxy } = getCurrentInstance();
${dictTypeKeyList.length ? `\nconst { ${dictTypeKeyList.join(', ')} } = useDict(${dictTypeStrList.join(', ')});\n` : ''}
const emit = defineEmits(['closeDialog']);

const props = defineProps({
  id: {
    type: Number,
    default: null,
  },
  title: {
    type: String,
    default: false,
  }
});

// ${data.tableNotes}表单
const ${data.tableName}FormRef = ref(null);

// 弹窗开关
const open = ref(false);

// 表单数据
const form = ref<${caseTableName}Record>({});

// 表单校验
const rules = ref({${rules}
});

// 加载
const loading = ref(false);

/** 获取${data.tableNotes}详情 */
function getData() {
  reset();
  if (isEmpty(props.id)) {
    open.value = true;
  } else {
    get${caseTableName}Api(props.id).then(response => {
      form.value = response.data;
      open.value = true;
    }).catch(() => {
      closeDialog(false);
    })
  }
}

/** 表单重置 */
function reset() {
  form.value = {${editParams}
  };
}

/** 关闭弹窗 */
function closeDialog(refresh: boolean) {
  open.value = false;
  emit('closeDialog', refresh);
}

/** 提交按钮 */
function submitForm() {
  // @ts-ignore
  ${data.tableName}FormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      if (isEmpty(form.value.${tableKey})) {
        add${caseTableName}Api(form.value).then(() => {
          // @ts-ignore
          proxy.$modal.msgSuccess('新增成功');
          loading.value = false;
          closeDialog(true);
        }).catch(() => {
          loading.value = false;
        });
      } else {
        update${caseTableName}Api(form.value).then(() => {
          // @ts-ignore
          proxy.$modal.msgSuccess('修改成功');
          loading.value = false;
          closeDialog(true);
        }).catch(() => {
          loading.value = false;
        });
      }
    }
  });
}

watch(open, (val) => {
  if (!val) {
    closeDialog(false);
  }
});

getData();
</script>

<template>
  <!-- ${data.tableNotes}编辑对话框 -->
  <el-dialog :title="title" v-model="open" width="700px" append-to-body :close-on-click-modal="false">
    <el-form ref="${data.tableName}FormRef" :model="form" :rules="rules" :inline="true" label-width="80px">${editFormItems}
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" v-debounce="submitForm" :loading="loading">确 定</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>

</style>`

  const detailVue = `<script setup lang="ts" name="${caseTableName}Detail">
import { get${caseTableName}Api } from '@/api/system/${data.tableName}';

${dictTypeKeyList.length ? `const { ${dictTypeKeyList.join(", ")} } = useDict(${dictTypeStrList.join(", ")});\n` : ''}
const emit = defineEmits(['closeDialog']);

const props = defineProps({
  id: {
    type: Number,
    default: null,
  },
  title: {
    type: String,
    default: false,
  }
});

const open = ref(false);

const form = ref<${caseTableName}Record>({});

/** 获取${data.tableNotes}详情 */
function getData() {
  if (isEmpty(props.id)) {
    open.value = true;
  } else {
    get${caseTableName}Api(props.id).then(response => {
      form.value = response.data;
      open.value = true;
    }).catch(() => {
      closeDialog(false);
    })
  }
}

/** 关闭弹窗 */
function closeDialog(refresh: boolean) {
  open.value = false;
  emit('closeDialog', refresh);
}

watch(open, (val) => {
  if (!val) {
    closeDialog(false);
  }
});

getData();
</script>

<template>
  <!-- ${data.tableNotes}详情对话框 -->
  <el-dialog :title="title" v-model="open" width="700px" append-to-body>
    <div class="detail-form">
      <el-form ref="${data.tableName}Form" :model="form" label-width="80px">${detailFormItems}
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>

</style>`

  const apiTs = `/** 查询${data.tableNotes}列表 */
export function list${caseTableName}Api(query: ${caseTableName}Record): Promise<ApiRowsRecord<${caseTableName}Record[]>> {
  return request({
    url: \`/${data.apiUrl}/list\`,
    method: 'get',
    params: query
  });
}

/** 查询${data.tableNotes}详细 */
export function get${caseTableName}Api(id: number): Promise<ApiDataRecord<${caseTableName}Record>> {
  return request({
    url: \`/${data.apiUrl}/\${id}\`,
    method: 'get'
  });
}

/** 新增${data.tableNotes} */
export function add${caseTableName}Api(data: ${caseTableName}Record): Promise<ApiRecord> {
  return request({
    url: \`/${data.apiUrl}\`,
    method: 'post',
    data: data
  });
}

/** 修改${data.tableNotes} */
export function update${caseTableName}Api(data: ${caseTableName}Record): Promise<ApiRecord> {
  return request({
    url: \`/${data.apiUrl}\`,
    method: 'put',
    data: data
  });
}

/** 删除${data.tableNotes} */
export function del${caseTableName}Api(id: number[]): Promise<ApiRecord> {
  return request({
    url: \`/${data.apiUrl}/\${id}\`,
    method: 'delete'
  });
}`

  let domanItems = '';
  for (let i = 1; i <= 30; i++) {
    let domanItem = ''
    for (let key of data.tableList) {
      if (key.columnName == tableKey) {
        domanItem += `${key.columnName}: ${i}, `
      } else if (key.boxType == BOX_TYPE_ENUM.datePicker) {
        domanItem += `${key.columnName}: '${parseTime(new Date().getTime() + i * 1000)}', `
      } else if (key.boxType == BOX_TYPE_ENUM.radio) {
        domanItem += `${key.columnName}: '${Math.floor(Math.random() * 2)}', `
      } else if (key.boxType == BOX_TYPE_ENUM.select) {
        domanItem += `${key.columnName}: '${Math.floor(Math.random() * 2)}', `
      } else if (key.boxType == BOX_TYPE_ENUM.checkbox) {
        domanItem += `${key.columnName}: ['${Math.floor(Math.random() * 2)}', '${Math.floor(Math.random() * 2)}'], `
      } else if (key.columnType == COLUMN_TYPE_MAP[JAVA_TYPE_ENUM.integer]) {
        domanItem += `${key.columnName}: ${Math.floor(Math.random() * 9) + 1}, `
      } else {
        domanItem += `${key.columnName}: '${key.columnNotes}', `
      }
    }
    domanItems += `
  { ${domanItem}},`
  }

  const recordTs = `/**
 * ${data.tableNotes} 类型
 */
interface ${caseTableName}Record extends ColumnRecord {${records}
}`

  const mockTs = `import { cloneDeep, } from 'lodash-es';

let ${data.tableName}List: ${caseTableName}Record[] = [${domanItems}
];

const mocks: MockRecord[] = [
  {
    method: 'get',
    url: '/api/${data.apiUrl}/list',
    response(option) {
      const copyList = cloneDeep(${data.tableName}List);
      
      let resList = ${data.tableName}List;
      
      if (option.query.pageNum) {
        resList = copyList.splice((option.query.pageNum - 1) * option.query.pageSize, option.query.pageSize);
      }
      
      const resData: responseType = {
        code: 200,
        msg: '查询成功',
        total: ${data.tableName}List.length,
        ...(option.query.pageNum ? { rows: resList } : { data: resList })
      }
      
      return resData;
    }
  },
  {
    method: 'get',
    url: '/api/${data.apiUrl}/:${tableKey}',
    response(option) {
      const res${caseTableName} = ${data.tableName}List.find(item => item.${tableKey} == option.query.${tableKey});

      const resData: responseType = {
        code: res${caseTableName} ? 200 : 500,
        msg: res${caseTableName} ? '查询成功' : '查询失败',
        data: res${caseTableName},
      }
      
      return resData;
    }
  },
  {
    method: 'post',
    url: '/api/${data.apiUrl}',
    response(option) {
      const new${caseTableName} = option.body;
      
      new${caseTableName}.${tableKey} = ${data.tableName}List.length + 1;
      ${data.tableName}List.unshift(new${caseTableName});
      
      const resData: responseType = {
        code: 200,
        msg: '新增成功',
      }
      
      return resData;
    }
  },
  {
    method: 'put',
    url: '/api/${data.apiUrl}',
    response(option) {
      const new${caseTableName} = option.body;
      
      const index = ${data.tableName}List.findIndex(item => item.${tableKey} == new${caseTableName}.${tableKey});
      
      ${data.tableName}List.splice(index, 1, new${caseTableName});
      
      const resData: responseType = {
        code: 200,
        msg: '修改成功',
      }
      
      return resData;
    }
  },
  {
    method: 'delete',
    url: '/api/${data.apiUrl}/:${tableKey}s',
    response(option) {
      const ${tableKey}s = option.query.${tableKey}s.split(',');
      
      const filterList = ${data.tableName}List.filter(item => !${tableKey}s.includes(String(item.${tableKey})));
      
      ${data.tableName}List = filterList;
      
      const resData: responseType = {
        code: 200,
        msg: '删除成功',
      }
      return resData;
    }
  }
];

export default mocks;`

  const viewData: ViewPageRecord = {
    index: indexVue,
    edit: editVue,
    detail: detailVue,
    api: apiTs,
    record: recordTs,
    mock: mockTs,
  }
  return viewData;
}

function titleCase(str) {
  return str.slice(0, 1).toUpperCase() + str.slice(1);
}